//
//  CommentViewController.m
//  WisdomZhuHai
//
//  Created by JasonLee on 15/1/27.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "CommentViewController.h"
#import "TransforController.h"
#import "CommentSendViewController.h"
#import "PullTableView.h"

@interface CommentViewController ()<UITableViewDataSource, UITableViewDelegate, refreshAfterSentDelegate, PullTableViewDelegate>

@property (nonatomic,assign) int currentIndex;

@property(nonatomic, strong)PullTableView *view_table;
@property(nonatomic, strong)NSMutableArray *array_data;
@property(nonatomic, strong)NSMutableArray *array_height_cell;
@property(nonatomic, strong)UILabel *lb_headerText;

@end

@implementation CommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initView];
    self.currentIndex = -1;
    [self setEnableRefresh:NO];
    [self setEnableLoadMore:YES];
    [self getCommentList];
    [self.view setFrame:CGRectMake(0, 0, 320, [UIScreen mainScreen].bounds.size.height)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initView{
    UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:-65];
    [self.view addSubview:view_navigationBar];
    
    UIBarButtonItem *btn_gotoSendComment = [[UIBarButtonItem alloc]initWithTitle:@"发表评论" style:UIBarButtonItemStyleDone target:self action:@selector(gotoSendComment)];
    self.navigationItem.rightBarButtonItem = btn_gotoSendComment;
    self.navigationItem.title = @"全部评论";
    self.view_table = [[PullTableView alloc]initWithFrame:CGRectMake(0, 65, 320, self.view.frame.size.height - HEIGHT_NAVIGATION_BAR - HEIGHT_STATUS_BAR) style:UITableViewStylePlain];
    self.view_table.dataSource = self;
    self.view_table.delegate = self;
    self.view_table.pullDelegate = self;
    self.view_table.tableFooterView = [[UIView alloc]init];
    UIView *view_header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
    self.view_table.tableHeaderView = view_header;
    self.lb_headerText = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 310, 44)];
    self.lb_headerText.textAlignment = UITextAlignmentLeft;
    self.lb_headerText.text = @"共有0条评论";
    UILabel *lb_divider = [[UILabel alloc]initWithFrame:CGRectMake(10, 44, 300, 1)];
    lb_divider.backgroundColor = [TransforController getColorWithRed:225 andGreen:225 andBlue:225 andAlpha:1];
    [view_header addSubview:lb_divider];
    self.lb_headerText.font = [TransforController getFontWithFont:@"Arial" andSize:14.0];
    [view_header addSubview:self.lb_headerText];
    [self.view addSubview:self.view_table];
    
    self.array_height_cell = [[NSMutableArray alloc]init];
    self.array_data = [[NSMutableArray alloc]init];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.array_data count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"%s || indexPath: %ld", __FUNCTION__, (long)indexPath.row);
    if([self.array_height_cell count] < 1){
        return 80;
    }else{
//        UITableViewCell *cell= self.array_height_cell[indexPath.row];
//        UILabel *lb_comment = (UILabel *)[cell viewWithTag:70004];
//        CGFloat height = [lb_comment.text sizeWithFont:lb_comment.font constrainedToSize:CGSizeMake(320, MAXFLOAT) lineBreakMode:lb_comment.lineBreakMode].height + 10;
//        [lb_comment setFrame:CGRectMake(lb_comment.frame.origin.x, lb_comment.frame.origin.y, lb_comment.frame.size.width, height)];
        return ([self.array_height_cell[indexPath.row] floatValue] + 55);
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    NSArray *nibView = [[NSBundle mainBundle]loadNibNamed:@"SportsCell" owner:self options:nil];
//    if([self.array_data count])
    NSDictionary *dic_temp = [NSDictionary dictionaryWithDictionary:[self.array_data objectAtIndex:indexPath.row]];
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HotCommentsMiddle"];
    cell = [nibView objectAtIndex:0	];
    NSString *imgUrl = [Common valueForKey:@"user_img" dic:dic_temp];
    if(![imgUrl isEqualToString:@""]){
        UIImageView *img_head = [(UIImageView *)[cell viewWithTag:70001] retain];
        [img_head setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
    }
    UILabel *lb_username = (UILabel *)[cell viewWithTag:70002];
    lb_username.text = [dic_temp objectForKey:@"username"];
    UILabel *lb_datetime = (UILabel *)[cell viewWithTag:70003];
    lb_datetime.text = [dic_temp objectForKey:@"created_at"];
    UILabel *lb_comment = (UILabel *)[cell viewWithTag:70004];
    NSString *string_temp = [dic_temp objectForKey:@"content"];
    lb_comment.text = string_temp;
    lb_comment.lineBreakMode = UILineBreakModeWordWrap;
    lb_comment.numberOfLines = 0;
    CGFloat height = [lb_comment.text sizeWithFont:lb_comment.font constrainedToSize:CGSizeMake(320, MAXFLOAT) lineBreakMode:lb_comment.lineBreakMode].height + 10;
    [lb_comment setFrame:CGRectMake(lb_comment.frame.origin.x, lb_comment.frame.origin.y, lb_comment.frame.size.width, height)];
    UIButton *btn_likeCount = (UIButton *)[cell viewWithTag:70005];
    btn_likeCount.titleLabel.text = [dic_temp objectForKey:@"good"];
    [btn_likeCount setTitle:[dic_temp objectForKey:@"good"] forState:UIControlStateNormal];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.array_height_cell[indexPath.row] = [NSString stringWithFormat:@"%f",height];
//    NSLog(@"%s || indexPath: %ld", __FUNCTION__, (long)indexPath.row);
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%s || indexPath:%d", __FUNCTION__, indexPath.row);
}

- (void)getCommentList{
    [[ProtocolManager shareInstance]getCommentListWithTargetId:self.target_id andType:self.type andReturnCount:10 andBeginNo:_currentIndex + 1 andTarget:self andSelector:@selector(getCommentListCallBack:)];
}

- (void)getCommentListCallBack:(NSDictionary *)dic{
    NSLog(@"%s || dic:%@ and %d", __FUNCTION__, dic, (dic == nil));
    if(dic == nil){
        [self resetPullTableViewState];
        return;
    }
    if([[Common valueForKey:@"respCode" dic:dic]isEqualToString:@"000"]){
        
        NSArray *array_temp = [NSMutableArray arrayWithArray:[Common valueForKey:@"comments" dic:dic]];
//        self.array_data = [NSArray arrayWithArray:[Common valueForKey:@"comments" dic:dic]];
        
        for(int i = 0; i < array_temp.count; i++){
            UILabel *lb_temp = [[UILabel alloc]init];
            lb_temp.text = [Common valueForKey:@"content" dic:array_temp[i]];
            lb_temp.lineBreakMode = UILineBreakModeWordWrap;
            lb_temp.numberOfLines = 0;
            CGFloat height = [lb_temp.text sizeWithFont:lb_temp.font constrainedToSize:CGSizeMake(320, MAXFLOAT) lineBreakMode:lb_temp.lineBreakMode].height + 10;
            [self.array_height_cell addObject:[NSString stringWithFormat:@"%f",height]];
            [self.array_data addObject:array_temp[i]];
        }
        [self.view_table reloadData];
        self.lb_headerText.text = [NSString stringWithFormat:@"共有%d条评论", [[Common valueForKey:@"comment_cnt" dic:dic]intValue]];
        if (array_temp.count < 10 ) {
            [self setEnableLoadMore:NO];
        }
        else {
            [self setEnableLoadMore:YES];
        }
        self.currentIndex += [array_temp count];
    }else{
        self.array_height_cell = [[NSMutableArray alloc]init];
        self.array_data = [[NSMutableArray alloc]init];
    }
    
    [self resetPullTableViewState];
}

- (void)gotoSendComment{
    NSLog(@"%s || sendComment jump.", __FUNCTION__);
    CommentSendViewController *commentSendViewController = [[CommentSendViewController alloc]init];
    commentSendViewController.target_id = self.target_id;
    commentSendViewController.type = self.type;
    commentSendViewController.hidesBottomBarWhenPushed = YES;
    commentSendViewController.refreshDelegate = self;
    [self.navigationController pushViewController:commentSendViewController animated:YES];
}

- (void)refreshTableView{
    NSLog(@"%s || actions'been actived.", __FUNCTION__);
    [self pullTableViewDidTriggerRefresh:self.view_table];
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = -1;
    self.array_height_cell = [[NSMutableArray alloc]init];
    self.array_data = [[NSMutableArray alloc]init];
    [self getCommentList];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getCommentList];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

- (void)setEnableRefresh:(BOOL)flag
{
    ((PullTableView*)self.view_table).enableRefresh = flag;
}

- (void)setEnableLoadMore:(BOOL)flag
{
    ((PullTableView*)self.view_table).enableLoadingMore = flag;
}

- (void)setPullRefreshDate:(NSDate *)date
{
    ((PullTableView*)self.view_table).pullLastRefreshDate = date;
}

- (void)setPullTableIsRefreshing:(BOOL)refreshing
{
    ((PullTableView*)self.view_table).pullTableIsRefreshing = refreshing;
}
- (void)setPullTableIsLoadMore:(BOOL)loadMore
{
    ((PullTableView*)self.view_table).pullTableIsLoadingMore = loadMore;
}

- (void)reloadRowIndexInSection:(int)section row:(int)row
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.view_table reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

@end
